package cn.sdormitory.basedata.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.sdormitory.basedata.dao.BClassDao;
import cn.sdormitory.basedata.dao.BDormitoryDao;
import cn.sdormitory.basedata.dao.BStudentDao;
import cn.sdormitory.basedata.dao.DormitoryBedDao;
import cn.sdormitory.basedata.dto.AssignClassDTO;
import cn.sdormitory.basedata.dto.AssignDormDTO;
import cn.sdormitory.basedata.dto.StudentExportDTO;
import cn.sdormitory.basedata.entity.BClass;
import cn.sdormitory.basedata.entity.BDormitory;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.basedata.entity.DormitoryBed;
import cn.sdormitory.basedata.service.BClassService;
import cn.sdormitory.basedata.service.BDormitoryService;
import cn.sdormitory.basedata.service.BStudentService;
import cn.sdormitory.basedata.vo.BStudentInfoVo;
import cn.sdormitory.common.api.CommonResult;
import cn.sdormitory.common.constant.CommonConstant;
import cn.sdormitory.common.exception.ApiException;
import cn.sdormitory.common.utils.ContainerUtil;
import cn.sdormitory.common.utils.PropertiesUtils;
import cn.sdormitory.common.utils.RedisUtils;
import cn.sdormitory.common.utils.StringUtils;
import cn.sdormitory.login.BStudentDetails;
import cn.sdormitory.request.HttpRequest;
import cn.sdormitory.sys.dao.SysDictDetailDao;
import cn.sdormitory.sys.dao.SysUserDao;
import cn.sdormitory.sys.entity.SysDictDetail;
import cn.sdormitory.sys.entity.SysUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @创建人：zhouyang
 * @创建时间：2020/11/10 16:30
 * @version：V1.0
 */
@Slf4j
@Service("bStudentService")
public class BStudentServiceImpl extends ServiceImpl<BStudentDao, BStudent> implements BStudentService{
    @Resource
    private BClassService bClassService;
    @Resource
    private SysDictDetailDao sysDictDetailDao;
    @Resource
    private BDormitoryService bDormitoryService;
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private BClassDao bClassDao;

    @Autowired
    BDormitoryDao bDormitoryDao;

    @Autowired
    DormitoryBedDao dormitoryBedDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public IPage<BStudent> getPage(Map<String, Object> params) {
        int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
        int pageNum = Integer.parseInt(String.valueOf(params.get("pageNum")));

        String studentName = (String) params.get("studentName");
        String studentNo = (String) params.get("studentNo");
        String className = (String) params.get("className");
        String buildingNo = (String) params.get("buildingNo");
        String storey = (String) params.get("storey");
        String dormitoryNo = (String) params.get("dormitoryNo");
        String status = (String) params.get("status");

        LambdaQueryWrapper<BStudent> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(studentName)) {
            wrapper.like(BStudent::getStudentName, studentName);
        }
        if (StrUtil.isNotEmpty(studentNo)) {
            wrapper.eq(BStudent::getStudentNo, studentNo);
        }
        if (StrUtil.isNotEmpty(className)) {
            wrapper.eq(BStudent::getClassName, className);
        }
        if (StrUtil.isNotEmpty(buildingNo)) {
            wrapper.eq(BStudent::getBuildingNo, buildingNo);
        }
        if (StrUtil.isNotEmpty(storey)) {
            wrapper.eq(BStudent::getStorey, storey);
        }
        if (StrUtil.isNotEmpty(dormitoryNo)) {
            wrapper.eq(BStudent::getDormitoryNo, dormitoryNo);
        }
        if (StrUtil.isNotEmpty(status)) {
            wrapper.eq(BStudent::getStatus, status);
        }
        String isGraduated = (String)params.get("isGraduated");
        if(StrUtil.isNotEmpty(isGraduated)){
            wrapper.eq(BStudent::getIsGraduated,isGraduated);
        }
//        wrapper.eq(BStudent::getIsGraduated,"0");
        wrapper.orderByDesc(BStudent::getCreateTime);
        wrapper.apply(params.get(CommonConstant.SQL_FILTER) != null, (String) params.get(CommonConstant.SQL_FILTER));
        return page(new Page<>(pageNum, pageSize), wrapper);
    }

    @Override
    public BStudent getBStudentById(Long id) {
        return getById(id);
    }

    @Override
    public int create(BStudent bStudent) {

        //插入当前学生班级信息
        BClass bClass = bClassService.getBClassById(bStudent.getClassId());
        bStudent.setClassName(bClass.getClassName());

        //插入当前学生住宿信息
        Long dormitoryId = bStudent.getBdormitoryId();
        Long bedId = bStudent.getBedId();
        BDormitory bDormitory = bDormitoryDao.selectById(dormitoryId);
        DormitoryBed dormitoryBed = dormitoryBedDao.selectById(bedId);
        if(bDormitory != null){
            bStudent.setBdormitoryId(dormitoryId);
            bStudent.setBuildingNo(bDormitory.getBuildingNo());
            bStudent.setStorey(bDormitory.getStorey());
            bStudent.setDormitoryNo(bDormitory.getDormitoryNo());
            bStudent.setStatus(CommonConstant.VALID_STATUS);
            if(dormitoryBed != null){
                bStudent.setBedId(bedId);
                bStudent.setBedNo(dormitoryBed.getBedNo());
            }
        }else{
            bStudent.setStatus(CommonConstant.VALID_STATUS0);
        }
        bStudent.setIsGraduated("0");
        int num = this.baseMapper.insert(bStudent);

        //更新宿舍床位信息
        if(num > 0 && dormitoryBed != null){
            dormitoryBed.setStudentId(bStudent.getId());
            dormitoryBedDao.updateById(dormitoryBed);
        }
        return num;
    }

//    @Override
//    public int delete(Long id) {
//        return this.baseMapper.deleteById(id);
//    }

    @Override
    public int update(Long id, BStudent bStudent) {
        int flag = 0;
        int num = 0;
        //当前id在数据库中的学生信息
        BStudent bStudentInfo = this.baseMapper.selectById(id);
        //清空当前学生床位
        DormitoryBed bed = dormitoryBedDao.selectById(bStudentInfo.getBedId());
        if(bed != null){
            flag = this.dormitoryBedDao.update(bed, new UpdateWrapper<DormitoryBed>().lambda()
                    .set(DormitoryBed::getStudentId, null)
                    .eq(DormitoryBed::getId, bed.getId()));
        }

        //根据班级ID查询班级名称
        Long classId = bStudent.getClassId();
        BClass bClass = bClassService.getBClassById(classId);
        if(bClass == null){
            bStudent.setClassName(null);
        }else {
            bStudent.setClassName(bClass.getClassName());
        }

        //更新当前学生住宿信息
        Long dormitoryId = bStudent.getBdormitoryId();
        Long bedId = bStudent.getBedId();
        BDormitory bDormitory = bDormitoryDao.selectById(dormitoryId);
        DormitoryBed dormitoryBed = dormitoryBedDao.selectById(bedId);

        if(bDormitory != null){
            bStudent.setBdormitoryId(dormitoryId);
            bStudent.setBuildingNo(bDormitory.getBuildingNo());
            bStudent.setStorey(bDormitory.getStorey());
            bStudent.setDormitoryNo(bDormitory.getDormitoryNo());
            bStudent.setStatus(CommonConstant.VALID_STATUS);
            if(dormitoryBed != null){
                bStudent.setBedId(bedId);
                bStudent.setBedNo(dormitoryBed.getBedNo());
                bStudent.setId(id);
                num = this.baseMapper.updateById(bStudent);
            }else {
                num = this.baseMapper.update(bStudent, new UpdateWrapper<BStudent>().lambda()
                        .set(BStudent::getBedId,null).set(BStudent::getBedNo,null)
                        .eq(BStudent::getId,id));
            }
        }else{
            num = this.baseMapper.update(bStudent, new UpdateWrapper<BStudent>().lambda()
                    .set(BStudent::getStatus, "0")
                    .set(BStudent::getBdormitoryId, null)
                    .set(BStudent::getBuildingNo, null)
                    .set(BStudent::getStorey, null).set(BStudent::getDormitoryNo, null)
                    .set(BStudent::getBedId,null).set(BStudent::getBedNo,null)
                    .eq(BStudent::getId,id));
        }
        //更新宿舍床位信息
        if(num > 0 && dormitoryBed != null){
            dormitoryBed.setStudentId(bStudent.getId());
            dormitoryBedDao.updateById(dormitoryBed);
        }
        return num;
    }

//    @Override
//    public int deleteByIds(String[] ids) {
//        String[] studentNos=new String[ids.length];
//        for(int i=0;i<ids.length;i++){
//            BStudent bStudent=this.getBStudentById(Long.parseLong(ids[i]));
//            String studentNo=bStudent.getStudentNo();
//            studentNos[i]=studentNo;
//        }
//        this.removePerson(studentNos);
//        return this.baseMapper.deleteBatchIds(Arrays.asList(ids));
//    }


    @Override
    public int resetPwd(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        int update = 0;
        for(Long stuId : idList){
            BStudent student = this.baseMapper.selectById(stuId);
            student.setStudentPassword(passwordEncoder.encode("123456"));
            student.setModifyTime(new Date());
            this.baseMapper.updateById(student);
            update ++;
        }
        if(update == ids.length){
            return 0;
        }else if(update < ids.length && update > 0){
            return 1;
        }else {
            return -1;
        }
    }

    @Override
    public CommonResult<Object> addFaceInfo(BStudent student) {
        LambdaUpdateWrapper<BStudent> wrapper = Wrappers.<BStudent>lambdaUpdate()
                .eq(BStudent::getId, student.getId())
                .set(BStudent::getStuPhoto, student.getStuPhoto());
        int rows = baseMapper.update(null, wrapper);
        return rows > 0 ? CommonResult.success(rows) : CommonResult.failed();
    }

    @Override
    public Map<Long, String> findIdAndNameMappings(List<Long> ids) {
        if (ContainerUtil.isEmpty(ids)) {
            return Collections.emptyMap();
        }
        List<BStudent> list = list(Wrappers.<BStudent>lambdaQuery()
                .select(BStudent::getId, BStudent::getStudentName)
                .in(BStudent::getId, ids));
        return ContainerUtil.toMap(list, BStudent::getId, BStudent::getStudentName);
    }

    @Override
    public int deleteByIds(Long[] ids) {
        List<Long> idList = Arrays.asList(ids);
        int update = 0;
        for(Long stuId : idList){
            BStudent student = this.baseMapper.selectById(stuId);
            //住宿学生清空宿舍床位
            if("1".equals(student.getStatus())){
                LambdaQueryWrapper<DormitoryBed> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(DormitoryBed::getStudentId,stuId);
                DormitoryBed dormitoryBed = dormitoryBedDao.selectOne(wrapper);
                if(dormitoryBed != null){
                    int num = this.dormitoryBedDao.update(dormitoryBed, new UpdateWrapper<DormitoryBed>().lambda()
                            .set(DormitoryBed::getStudentId, null)
                            .eq(DormitoryBed::getId, dormitoryBed.getId()));
                }
            }
            //逻辑删除
            update = this.baseMapper.update(student, new UpdateWrapper<BStudent>().lambda()
                    .set(BStudent::getIsGraduated, "1")
                    .set(BStudent::getStatus, "0")
                    .set(BStudent::getBdormitoryId, null)
                    .set(BStudent::getBuildingNo, null)
                    .set(BStudent::getStorey, null).set(BStudent::getDormitoryNo, null)
                    .set(BStudent::getBedId,null).set(BStudent::getBedNo,null)
                    .eq(BStudent::getId,stuId));
        }
        return update;
//        return this.baseMapper.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    public int updateStatus(Long id, String status) {
//        BStudent student = this.baseMapper.selectById(id);
        return this.baseMapper.update(null, new UpdateWrapper<BStudent>().lambda()
                .set(BStudent::getStatus, "0")
                .set(BStudent::getBdormitoryId, null)
                .set(BStudent::getBuildingNo, null)
                .set(BStudent::getStorey, null)
                .set(BStudent::getDormitoryNo, null)
                .set(BStudent::getBedId,null)
                .set(BStudent::getBedNo,null)
                .eq(BStudent::getId,id));
//        BStudent bStudent = new BStudent();
//        bStudent.setId(id);
//        bStudent.setStatus(status);
//        return this.baseMapper.updateById(bStudent);
    }

    @Override
    public BStudent getByStudentNo(String studentNo) {
        return this.baseMapper.selectOne(new LambdaQueryWrapper<BStudent>().eq(BStudent::getStudentNo, studentNo));
    }

    @Override
    public String setPerson(BStudent bStudent) {
        String key = PropertiesUtils.get("device.properties", "sdormitory.device1.key");
        String ip = PropertiesUtils.get("device.properties","sdormitory.device1.ip");
        List pairs = new ArrayList();
        String base64;
        base64 = Base64.encodeBase64String(bStudent.getPhoto());
        pairs.add(new BasicNameValuePair("key",key));
        pairs.add(new BasicNameValuePair("id",bStudent.getStudentNo()));
        pairs.add(new BasicNameValuePair("name",bStudent.getStudentName()));
        pairs.add(new BasicNameValuePair("IC_NO",bStudent.getStudentNo()));
        pairs.add(new BasicNameValuePair("ID_NO",bStudent.getIdcard()));
        pairs.add(new BasicNameValuePair("photo",base64));
        pairs.add(new BasicNameValuePair("passCount","10000"));
        pairs.add(new BasicNameValuePair("startTs","-1"));
        pairs.add(new BasicNameValuePair("endTs","-1"));
        pairs.add(new BasicNameValuePair("visitor","false"));
        String object = HttpRequest.sendPost(ip+"/setPerson",pairs);
        return object;
    }

    @Override
    public String getPerson( String id) {
        String key = PropertiesUtils.get("device.properties", "sdormitory.device1.key");
        String ip = PropertiesUtils.get("device.properties","sdormitory.device1.ip");
        String object = HttpRequest.sendGet(ip+"/getPerson?key="+key+"&id="+id,null);
        return object;
    }

    @Override
    public String listPersonByNumber(int number, int offset) {
        String key = PropertiesUtils.get("device.properties", "sdormitory.device1.key");
        String ip = PropertiesUtils.get("device.properties","sdormitory.device1.ip");
        String object = HttpRequest.sendGet(ip+"/listPersonByNumber?key="+key+"&number="+number+"&offset="+offset,null);
        return object;
    }

    @Override
    public String removePerson(String [] studentNos) {
        StringBuffer sbstr=new StringBuffer("[");
        for (String str:studentNos){
            sbstr.append(str+",");
        }
        String astr=sbstr.toString();
        if(astr.length()>1){
            astr=astr.substring(0,astr.length()-1);
        }
        astr+="]";
        String key = PropertiesUtils.get("device.properties", "sdormitory.device1.key");
        String ip = PropertiesUtils.get("device.properties","sdormitory.device1.ip");
        //修复pairs直接传空报空指针问题
        List pairs = new ArrayList();
        pairs.add(new BasicNameValuePair("key",key));
        pairs.add(new BasicNameValuePair("id",astr));
        String object = HttpRequest.sendPost(ip+"/removePerson",pairs);
        return object;
    }

    @Override
    public JSONObject listRecordByNumber(Integer number, Integer offset, Integer dbtype) {
        String key = PropertiesUtils.get("device.properties", "sdormitory.device1.key");
        String ip = PropertiesUtils.get("device.properties","sdormitory.device1.ip");
        HttpClient client= new DefaultHttpClient();
        HttpPost request = new HttpPost(ip+"/listRecordByNumber?key="+key+"&dbtype="+dbtype+"&number="+number+"&offset="+offset);

        JSONObject object = null;
        try {
            HttpResponse resp = client.execute(request);
            HttpEntity entity = resp.getEntity();
            if(entity!=null){
                String result = EntityUtils.toString(entity,"UTF-8");//解析返回数据
                object = JSONObject.fromObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

    @Override
    public JSON removeRecord(double ts) {
        String key = PropertiesUtils.get("device.properties", "sdormitory.device1.key");
        String ip = PropertiesUtils.get("device.properties","sdormitory.device1.ip");
        HttpClient client= new DefaultHttpClient();
        HttpPost request = new HttpPost(ip+"/removeRecord?key="+key+"&ts="+ts);

        JSONObject object = null;
        try {
            HttpResponse resp = client.execute(request);
            HttpEntity entity = resp.getEntity();
            if(entity!=null){
                String result = EntityUtils.toString(entity,"UTF-8");//解析返回数据
                object = JSONObject.fromObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }


    @Override
    public String removePersonById(String id) {
        String key = PropertiesUtils.get("device.properties", "sdormitory.device1.key");
        String ip = PropertiesUtils.get("device.properties","sdormitory.device1.ip");
        //修复pairs直接传空报空指针问题
        List pairs = new ArrayList();
        pairs.add(new BasicNameValuePair("key",key));
        pairs.add(new BasicNameValuePair("id",id));
        String object = HttpRequest.sendPost(ip+"/removePerson",pairs);
        return object;
    }


    @Override
    public BStudent getByStuNoAndNameAndClassId(String studentNo, String studentName, Long classId) {
        LambdaQueryWrapper<BStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BStudent::getStudentNo, studentNo);

        if(!"".equals(studentName) && studentName!=null){
            wrapper.eq(BStudent::getStudentName, studentName);
        }
        if(!"".equals(classId) && classId!=null){
            wrapper.eq(BStudent::getClassId, classId);
        }
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public BStudent getByStuNoAndNameAndClassName(String studentNo, String studentName, String className) {
        LambdaQueryWrapper<BStudent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BStudent::getStudentNo, studentNo);
        wrapper.eq(BStudent::getStudentName, studentName);
        wrapper.eq(BStudent::getClassName, className);
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    public int insert(BStudent student) {
        if(student.getStudentName()==null ||student.getStudentName()==""){
            return -10;
        }
        if(student.getClassName()==null ||student.getClassName()==""){
            return -11;
        }
        if(student.getStudentNo()==null ||student.getStudentNo()==""){
            return -12;
        }
        if(student.getPhone()==null ||student.getPhone()==""){
            return -13;
        }
        BClass bClass=bClassService.getByClassName(student.getClassName());
        if(bClass==null){
            return -1;
        }

        //性别(字典表)
        SysDictDetail sysDictDetail=this.getSysDictDetailByLable(student.getSex(),"sys_user_sex");
        if(sysDictDetail!=null){
            student.setSex(sysDictDetail.getDictValue());
        }else{
            return -2;
        }
        //栋号(字典表)
        SysDictDetail sysDictDetai2=this.getSysDictDetailByLable(student.getBuildingNo(),"sys_building");
        if(sysDictDetai2==null){
            return -3;
        }
        //栋号(字典表)
        SysDictDetail sysDictDetai3=this.getSysDictDetailByLable(student.getStorey(),"sys_storey");
        if(sysDictDetai3==null){
            return -4;
        }
        if(sysDictDetai2!=null && sysDictDetai3!=null){
            BDormitory bDormitory=bDormitoryService.getByDormitoryInfo(sysDictDetai2.getDictValue(),sysDictDetai3.getDictValue(),student.getDormitoryNo());
            if(bDormitory!=null){
                student.setBuildingNo(sysDictDetai2.getDictValue());
                student.setStorey(sysDictDetai3.getDictValue());
                student.setBdormitoryId(bDormitory.getId());
            }else{
                return -5;
            }
        }
        BStudent student1=this.getByStudentNo(student.getStudentNo());
        if(student1==null){
            student.setClassId(bClass.getId());
            student.setStatus(CommonConstant.VALID_STATUS);
            return this.getBaseMapper().insert(student);
        }else{
            return -6;
        }

    }


    @Override
    public int insert1(BStudent student) {
        if(student.getStudentName()==null ||student.getStudentName()==""){
            return -10;
        }
        if(student.getClassName()==null ||student.getClassName()==""){
            return -11;
        }
        if(student.getStudentNo()==null ||student.getStudentNo()==""){
            return -12;
        }
        if(student.getPhone()==null ||student.getPhone()==""){
            return -13;
        }
        BClass bClass=bClassService.getByClassName(student.getClassName());
        if(bClass==null){
            return -1;
        }

        //性别(字典表)
        SysDictDetail sysDictDetail=this.getSysDictDetailByLable(student.getSex(),"sys_user_sex");
        if(sysDictDetail!=null){
            student.setSex(sysDictDetail.getDictValue());
        }else{
            return -2;
        }

        BStudent student1=this.getByStudentNo(student.getStudentNo());
        if(student1==null){
            student.setClassId(bClass.getId());
            student.setStatus(CommonConstant.VALID_STATUS0);
            return this.getBaseMapper().insert(student);
        }else{
            return -6;
        }

    }

    @Override
    public SysDictDetail getSysDictDetailByLable(String dictLabel, String dictType) {
        LambdaQueryWrapper<SysDictDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictDetail::getDictLabel, dictLabel);
        wrapper.eq(SysDictDetail::getDictType, dictType);
        return sysDictDetailDao.selectOne(wrapper);
    }

    @Override
    public List<BStudentInfoVo> getStuInfoByClassId(Long classId) {
        return this.baseMapper.getStuInfoByClassId(classId);
    }

    @Override
    public CommonResult assignClass(AssignClassDTO dto) {
        if(dto.getClassId() == null){
            return CommonResult.failed("班级未选择！！！无法更改");
        }
        if(dto.getIds() == null || dto.getIds().size() <= 0){
            return CommonResult.failed("未选择需要更改班级的学生！！！");
        }
        BClass bClass = bClassService.getBClassById(dto.getClassId());
        for(Long id : dto.getIds()){
            BStudent bStudent = new BStudent();
            bStudent.setId(id);
            bStudent.setClassId(dto.getClassId());
            bStudent.setClassName(bClass.getClassName());
            this.baseMapper.updateById(bStudent);
        }
        return CommonResult.success("班级更换成功！！！");
    }

    @Override
    public CommonResult assignDorm(AssignDormDTO dto) {
        if(dto.getIds() == null || dto.getIds().size() <= 0){
            return CommonResult.failed("未选择需要更改宿舍的学生！！！");
        }
        if(StringUtils.isEmpty(dto.getBuildingNo())){
            return CommonResult.failed("未选择宿舍栋号！！！");
        }
        if(StringUtils.isEmpty(dto.getStorey())){
            return CommonResult.failed("未选择宿舍楼层！！！");
        }
        if(StringUtils.isEmpty(dto.getBdormitoryId())){
            return CommonResult.failed("未选择宿舍号！！！");
        }
        String[] split = dto.getBdormitoryId().split("-");
        Long dormitoryId = Long.parseLong(split[0]);
        String dormitoryNo = split[1];
        for(Long id : dto.getIds()){
            BStudent bStudent = new BStudent();
            bStudent.setId(id);
            bStudent.setBuildingNo(dto.getBuildingNo());
            bStudent.setStorey(dto.getStorey());
            bStudent.setDormitoryNo(dormitoryNo);
            bStudent.setBdormitoryId(dormitoryId);
            this.baseMapper.updateById(bStudent);
        }
        return CommonResult.success("宿舍更换成功！！！");
    }

    @Override
    public List<BStudent> getStuList(Map<String, Object> params) {        String studentName = (String) params.get("studentName");
        String studentNo = (String) params.get("studentNo");
        String className = (String) params.get("className");
        String buildingNo = (String) params.get("buildingNo");
        String storey = (String) params.get("storey");
        String dormitoryNo = (String) params.get("dormitoryNo");
        String status = (String) params.get("status");

        LambdaQueryWrapper<BStudent> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotEmpty(studentName)) {
            wrapper.like(BStudent::getStudentName, studentName);
        }
        if (StrUtil.isNotEmpty(studentNo)) {
            wrapper.eq(BStudent::getStudentNo, studentNo);
        }
        if (StrUtil.isNotEmpty(className)) {
            wrapper.eq(BStudent::getClassName, className);
        }
        if (StrUtil.isNotEmpty(buildingNo)) {
            wrapper.eq(BStudent::getBuildingNo, buildingNo);
        }
        if (StrUtil.isNotEmpty(storey)) {
            wrapper.eq(BStudent::getStorey, storey);
        }
        if (StrUtil.isNotEmpty(dormitoryNo)) {
            wrapper.eq(BStudent::getDormitoryNo, dormitoryNo);
        }
        if (StrUtil.isNotEmpty(status)) {
            wrapper.eq(BStudent::getStatus, status);
        }

        wrapper.orderByDesc(BStudent::getCreateTime);
        wrapper.apply(params.get(CommonConstant.SQL_FILTER) != null, (String) params.get(CommonConstant.SQL_FILTER));
        return this.baseMapper.selectList(wrapper);

    }

    @Override
    public BStudent getStudentById(String id) {
        BStudent bStudent = this.baseMapper.selectById(id);
        BClass bClassById = bClassService.getBClassById(bStudent.getClassId());
        SysUser sysUser = sysUserDao.selectById(bClassById.getClassTeacherId());
        bStudent.setTeacherName(sysUser.getUsername());
        bStudent.setTeacherPhone(sysUser.getPhone());
        return bStudent;
    }

    @Override
    public int syncStuPhoto(List<Map<String, String>> data){
        List<BStudent> allStudent = this.baseMapper.getAllStudent();
        try{
            for(Map<String, String> item : data){
                String stuId = item.get("stuId");
                String stuPhoto = item.get("stuPhoto");
                for (int i = 0; i < allStudent.size(); i++) {
                    if(Long.valueOf(stuId).equals(allStudent.get(i).getId())){
                        allStudent.get(i).setStuPhoto(stuPhoto);
                        this.baseMapper.updateById(allStudent.get(i));
                    }
                }
            }
            return 1;
        }catch (ApiException e){
            e.printStackTrace();
        }
        return -1;
    }

    @Override
    public List<StudentExportDTO> getStuListOrderByDor() {
        return this.baseMapper.getStuListOrderByDor();
    }

//    @Override
//    @Transactional
//    public boolean allocateDormitoryAndBed(Map<String, Long> map) {
//        Long studentId = map.get("studentId");
//        Long dormitoryId = map.get("dormitoryId");
//        Long bedId = map.get("bedId");
//
//        BDormitory dormitory = bDormitoryService.getBDormitoryById(dormitoryId);
//        BStudent student = this.baseMapper.selectById(studentId);
//        DormitoryBed dormitoryBed = dormitoryBedDao.selectById(bedId);
//
//        //更新学生住宿信息
//        student.setBuildingNo(dormitory.getBuildingNo());
//        student.setStorey(dormitory.getStorey());
//        student.setDormitoryNo(dormitory.getDormitoryNo());
//        student.setBdormitoryId(dormitoryId);
//        student.setBedNo(dormitoryBed.getBedNo());
//        student.setBedId(bedId);
//        this.baseMapper.updateById(student);
//
//        //更新宿舍床位信息
//        dormitoryBed.setStudentId(studentId);
//        dormitoryBedDao.updateById(dormitoryBed);
//
//        return true;
//    }

    @Override
    public int restoreStudent(BStudent bStudent) {
        return this.baseMapper.update(bStudent, new UpdateWrapper<BStudent>().lambda()
                .set(BStudent::getIsGraduated, "0")
                .eq(BStudent::getId,bStudent.getId()));
    }
}
